<script setup lang="ts">
	import { useCorps } from "./utils/hook";
	import Refresh from "@iconify-icons/ep/refresh";
	import BookmarkFill from "@iconify-icons/ri/bookmark-fill";
	import { PureTableBar } from "@/components/RePureTableBar";
	import { useRenderIcon } from "@/components/ReIcon/src/hooks";
	import { ref, nextTick, computed, onMounted } from "vue";
  import { message } from "@/utils/message";
  import { Printer } from '@element-plus/icons-vue'
  import { debounce } from "@pureadmin/utils";
  import {
    taskShowApi
  } from "@/api/taskApi";
	const {
		form,
		loading,
		columns,
    columnsTask,
		dataList,
		pagination,
		isShow,
		onSearch,
		resetForm,
		openDialog,
		handleSizeChange,
		handleCurrentChange,
		deviceDetection,
		handleDelete,
    userSelect,
    onDetail,
    receiveChange,
    openInvoicing,
    invoicingDetail,
    handleSelectionChange,
    multipleTableRef,
    tableData
	} = useCorps();
	const formRef = ref();
  const dialogDetail = ref(false)
  const detailData = ref()

  const seeDetail = (title: string, row: any) => {
    // dialogDetail.value = true
    // detailData.value = row
    if(title === '附件') {
      if(row.attachment && row.attachment.length > 0) {
        for (let item of row.attachment) {
          window.open(item.storageAddr, '_blank');
        }
      } else {
        message(`未上传文件`, { type: "error" });
      }
    } else if(title === '合同') {
      console.log(row)
      window.open(row.attachment.contract, '_blank');
    } else if(title === '清单') {
      if(row.attachment) {
        window.open(row.attachment.contract_list, '_blank');
      } else {
        message(`未上传文件`, { type: "error" });
      }
    } else if(title === '技术协议') {
      if(row.attachment) {
        window.open(row.attachment.technical_protocol, '_blank');
      } else {
        message(`未上传文件`, { type: "error" });
      }
    }

  }
  const tabIndex = ref(0)
  let arr: TableColumnList = [
    // {
    //   type: "selection",
    //   width: 60,
    //   slot: "selection",
    //   selectable: ({ status }) => {
    //     return status > 1 ? false : true;
    //   }
    // }
  ]
  const showExecTaskCountColumn = ref(true);
  const selectionColumns = ref(columnsTask)
  const selectionFlag = ref(true);
  const execTaskCount: any = {
    label: "可执行数",
    prop: "execTaskCount",
    minWidth: 100,
  }
  const columnsParent = ref()
  let [first, projectName, projectNo, projectTypeName,taskTypeName, ...rest] = columns;
  columnsParent.value = [first, projectName, projectNo, projectTypeName,taskTypeName, execTaskCount, ...rest];
  const taskInit = (index: number) => {
    tabIndex.value = index
    selectionFlag.value = false
    if(index === 0) {
      form.listType = 'assignedToMe'
      showExecTaskCountColumn.value = true
    } else if(index === 1) {
      form.listType = 'assignedExtraToMe'
      showExecTaskCountColumn.value = false
    } else {
      form.listType = 'principalByMe'
      selectionColumns.value = [...arr, ...columnsTask]
      showExecTaskCountColumn.value = false
    }

    if(index === 0) {
      columnsParent.value = [first, projectName, projectNo, projectTypeName,taskTypeName, execTaskCount, ...rest];
    } else {
      columnsParent.value = [...columns]
    }
    nextTick(() => {
      selectionFlag.value = true
      onSearch()
    })

  }
  const tabList = ref([
    {name: '指派给我'},
    {name: '抄送给我'},
    {name: '我负责的'},
  ])


  const tableRef = ref()


  const taskListRef = ref()
  // const tableData = ref([])
  const tableDataFlag = ref(true)
  const tableCheckboxchange = (val: any, row: any, index: number) => {

    tableDataFlag.value = false
    if (val) {
      tableData.value = []
      for (let item of dataList.value) {
        for (let child of item.taskList) {
          if(child.projectId === row.projectId) {
            tableData.value.push(child)
          } else {
            child.checkbox = false
          }
        }
      }
      let trueArr = []
      for (let item of tableData.value) {
        if(item.checkbox) {
          trueArr.push(item)
        }
      }
      // const maxObject = computed(() => {
      //   return Math.max(...trueArr.map(item => item.taskType));
      // });
      let arrIndex = 0
      for (let taskList of tableData.value) {
        if(taskList.childrens && taskList.childrens.length > 0) {
          arrIndex = taskList.childrens.length
        }
      }
      if(arrIndex === 3 && index >= 6) {
        index = index - arrIndex
      }
      if(arrIndex === 6 && index >= 9) {
        index = index - arrIndex
      }
      for (let i = 0; i < index; i++) {
        tableData.value[i].checkbox = true
        if(tableData.value[index].checkbox && tableData.value[index].childrens.length > 0) {
          for (let item of tableData.value[index].childrens) {
            item.checkbox = true
          }
        }
      }
    } else {

      for (let i = index; i < tableData.value.length; i++) {
        tableData.value[i].checkbox = false
      }
    }

    nextTick(() => {
      tableDataFlag.value = true
    })
  }


  const showAttachment = async(row: any) => {
    const res: any = await taskShowApi({ taskId: row?.prevTask?.taskId });

    let arr = [res?.result]
    // 过滤未开始
    const filteredData = computed(() => {
      return arr.map(category => ({
        ...category,
        childrens: category.childrens.filter(item => item.status !== 0)
      }));
    });

    detailData.value = filteredData.value
    dialogDetail.value = true
  }
  const projectTypeSelect = ref([
    {id:1,name: '生产'},
    {id:2,name: '生产实施'},
    {id:3,name: '集成(有生产)'},
    {id:4,name: '集成(无生产)'},
    {id:5,name: '外包'},
    {id:6,name: '贸易'},
  ])
  const contentRef = ref()
  const tableWidth = ref()
  onMounted(()=> {
    tableWidth.value = contentRef.value.offsetWidth
    observer.observe(contentRef.value)
  })
  const observer = new ResizeObserver(entries => {
    entries.forEach(entry => {
      tableWidth.value = entry.contentRect.width
    })
  })
  const expandedRows = ref([])
  const handleExpandChange = (row) => {
    const rowKey = row.projectId
    if (expandedRows.value.includes(rowKey)) {
      expandedRows.value = []
    } else {
      expandedRows.value = [rowKey]
    }
  }
  const getRowClassName = ({row, rowIndex}) => {
    if (rowIndex === 2) { // 假设你要修改第三行（索引为2）
      return 'custom-row-tr';
    }
    return '';
  }

  const openFile = (row: any) => {
    if(row.attachment && row.attachment.length > 0) {
      for (let item of row.attachment) {
        window.open(item.storageAddr, '_blank');
      }
    } else {
      message(`未上传文件`, { type: "error" });
    }

  }
</script>

<template>
	<div class="main">
		<el-form ref="formRef" :inline="true" :model="form"
			class="search-form bg-bg_color w-[99/100] pl-8 pt-[12px] overflow-auto">
			<el-form-item label="项目名称:">
				<!-- <el-select
				  v-model="form.projectId"
				  placeholder="请选择项目"
          class="!w-[180px]"
          clearable
          @change="onSearch"
				>
				  <el-option
				    v-for="item in form.projectSelect"
				    :key="item.projectId"
				    :label="item.projectName"
				    :value="item.projectId"

				  />
				</el-select> -->
        <el-input v-model="form.projectName" class="!w-[180px]" clearable placeholder="请输入项目名称" />
			</el-form-item>
      <el-form-item label="项目编号:">
      	<el-input v-model="form.projectNo" class="!w-[180px]" clearable placeholder="请输入项目编号" />
      </el-form-item>
      <el-form-item label="项目类型:">
      	<el-select
      	  v-model="form.projectType"
      	  placeholder="请选择"
      	  class="!w-[130px]"
      	  clearable
      	>
      	  <el-option
      	    v-for="item in projectTypeSelect"
      	    :key="item.id"
      	    :label="item.name"
      	    :value="item.id"

      	  />
      	</el-select>
      </el-form-item>
      <el-form-item label="电控:">
        <el-select
          v-model="form.electControl"
          placeholder="请选择"
          class="!w-[100px]"
          clearable
        >
          <el-option label="否" :value="0" />
          <el-option label="是" :value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="货款类型:">
        <el-select
          v-model="form.consignType"
          placeholder="请选择"
          class="!w-[100px]"
          clearable
        >
          <el-option label="发货款" :value="1" />
          <el-option label="到货款" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="收款标识:">
        <el-select
          v-model="form.receiptFull"
          placeholder="请选择"
          class="!w-[100px]"
          clearable
        >
          <el-option label="未结清" :value="0" />
          <el-option label="已结清" :value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="交付状态:">
        <el-select
          v-model="form.isDelive"
          placeholder="请选择"
          class="!w-[100px]"
          clearable
        >
          <el-option label="未交付" :value="0" />
          <el-option label="已交付" :value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="关键词:">
      	<el-input v-model="form.keyword" class="!w-[150px]" clearable placeholder="请输入关键词" />
      </el-form-item>
			<el-form-item>
				<el-button type="primary" :icon="useRenderIcon('ri:search-line')" :loading="loading" @click="onSearch">
					搜索
				</el-button>
				<el-button :icon="useRenderIcon(Refresh)" @click="resetForm(formRef)">
					重置
				</el-button>
			</el-form-item>
		</el-form>
    <keep-alive>
		<div ref="contentRef" :class="['flex', deviceDetection() ? 'flex-wrap' : '']">
			<PureTableBar :class="[isShow && !deviceDetection() ? '!w-[60vw]' : 'w-full']" v-if="selectionFlag"
				style="transition: width 220ms cubic-bezier(0.4, 0, 0.2, 1)" title=" " :columns="columnsParent"
				@refresh="onSearch">
        <template #title>
          <div class="flex-c">
            <el-button v-for="(item, index) in tabList" :key="index" :class="tabIndex === index?'taskMyActive':''" @click="taskInit(index)">
            {{item.name}}</el-button>
          </div>
        </template>
				<template #buttons>
          <!-- <el-affix :offset="100">
            <el-button type="primary" @click="openDialog('批量执行')" v-if="tabIndex === 2">
              批量执行
            </el-button>
          </el-affix> -->

				</template>

				<template v-slot="{ size, dynamicColumns }">
          <div ref="tableRef">


					<pure-table showOverflowTooltip table-layout="auto"
						:loading="loading" :size="size" adaptive :adaptiveConfig="{ offsetBottom: 108 }" row-key="projectId" @expand-change="handleExpandChange"
            :expand-row-keys="expandedRows"
						:data="dataList" :columns="dynamicColumns" :pagination="pagination" :default-expand-all="tabIndex === 2 ?true: false"
						:paginationSmall="size === 'small' ? true : false" :header-cell-style="{background: 'var(--el-fill-color-light)',
						color: 'var(--el-text-color-primary)'}" @page-size-change="handleSizeChange" @page-current-change="handleCurrentChange">
            <template #expand="props">
              <!-- style="width: 96%;margin: auto;" -->
              <div class="tableBox taskBox " ref="multipleTableRef" style="transform: translateZ(0);" :style="{'width': (tableWidth-20)+'px'}">
                <pure-table showOverflowTooltip table-layout="auto" border @selection-change="handleSelectionChange"
                  :adaptiveConfig="{ offsetBottom: 108 }" :data="props.row.taskList" :columns="selectionColumns"  row-key="taskId"
                  :tree-props="{ children: 'childrens', hasChildren: 'hasChildren' }" default-expand-all :row-class-name="getRowClassName"
                  :header-cell-style="{background: '#e3e3e3',color: 'var(--el-text-color-primary)'}">

                  <template #selection="{ row, $index }"  v-if="tabIndex === 2" >
                    <template v-if="row.parentId > 0">

                    </template>
                    <template v-else>
                      <el-checkbox label=" " checked disabled v-if ="row.status > 1" />
                      <el-checkbox v-model="row.checkbox" label=" " @change="(val)=>tableCheckboxchange(val, row, $index)" v-else />
                    </template>
                  </template>

                  <template #status="{ row }">
                    <el-tag type="info" v-if="row.status === 0">未开始</el-tag>
                    <el-tag type="warning" v-if="row.status === 1">进行中</el-tag>
                    <el-tag v-if="row.status === 2">挂起跳过</el-tag>
                    <el-tag type="success" v-if="row.status === 3">已完成</el-tag>
                    <el-tag type="danger" v-if="row.status === 4">已关闭</el-tag>
                  </template>
                  <template #realEndDate="{ row } ">
                    <div class="flex" style="justify-content: left;">
                      <div>{{row.realStartDate ?? '--'}}</div>
                      <div class="ml-[2px] mr-[2px]">至</div>
                      <div>{{row.realEndDate ?? '--'}}</div>
                    </div>
                  </template>
                  <template #assignedTo="{ row }">
                    <div class="assigneds">
                      <span v-for="(item, curr) in row.assigneds" :key="curr" class="str">
                        {{item.user?.name}}<span>, </span>
                      </span>
                    </div>
                  </template>
                  <template #assignedExtraTo="{ row }">
                    <div class="assigneds">
                      <span v-for="(item, curr) in row.assignedExtras" :key="curr" class="str">
                        {{item.user?.name}}<span>, </span>
                      </span>
                      <span v-if="row.assignedExtras && row.assignedExtras.length ===0">--</span>
                    </div>
                  </template>
                  <template #attachment="{ row }">
                    <el-button type="primary" plain size="small" @click="seeDetail('附件', props.row)">查看</el-button>
                  </template>
                  <template #operation=" { row } ">
                    <div v-if="tabIndex === 0 && row.taskType !== 1030000" style="display: inline-block;margin-right: 1px;">
                      <template v-if="row.invoice">
                        <el-button class="reset-margin" link type="primary" :size="size" @click="invoicingDetail(row, props.row)">
                          已开票
                        </el-button>
                      </template>
                      <template v-else>
                        <el-button class="reset-margin" link type="primary" :size="size"
                        v-if="row.status === 3 && (row.taskType === 2 || row.taskType === 7 || row.taskType === 11)"
                          @click="openInvoicing(row)">
                          开票
                        </el-button>
                      </template>

                      <!-- <el-button class="reset-margin" link type="danger" :size="size" v-if="row.status === 0 && row.showReceive"
                        @click="receiveChange(row)">
                        接收
                      </el-button> -->
                      <el-button class="reset-margin" link type="danger" :size="size" v-if="row.isReceive === 1"
                        @click="receiveChange(row)">
                        接收
                      </el-button>
                      <el-button class="reset-margin" link type="danger" :size="size" v-if="row.status !== 0 && row.status !== 3"
                        @click="openDialog('执行任务', row, props.row)">
                        执行
                      </el-button>
                    </div>
                    <el-button class="reset-margin" link type="primary" :size="size"
                      @click="seeDetail('合同', props.row)" v-if="row.taskType === 1010000">
                      合同
                    </el-button>

                    <el-button class="reset-margin" link type="primary" :size="size"
                      @click="onDetail(row)">
                      详情
                    </el-button>
                    <el-button class="reset-margin" link type="primary" :size="size" v-if="row.taskType !== 1030000"
                      @click="openDialog('日志', row)">
                      日志
                    </el-button>
                    <!-- <el-button class="reset-margin" link type="primary" :size="size" v-if="row.showPrevTask" @click="showAttachment(row)">
                      前置
                    </el-button> -->
                    <el-button class="reset-margin" link type="primary" :size="size" v-if="row.prevTask" @click="showAttachment(row)">
                      前置
                    </el-button>
                  </template>
                </pure-table>

              </div>
            </template>
            <template #isDelive="{row}">
              <el-tag type="success" v-if="row.isDelive === 1">已交付</el-tag>
              <el-tag type="info" v-else>未交付</el-tag>
            </template>
            <template #receiptFull="{row}">
              <el-tag size="small" type="success" v-if="row.receiptFull === 1">已结清</el-tag>
              <el-tag size="small" type="info" v-else>未结清</el-tag>
            </template>
            <template #taskTypeName="scope">
              <span>{{scope.row.taskTypeName || '--'}}</span>

              <!-- <el-button :icon="useRenderIcon(BookmarkFill)">
                {{scope.row.childTaskTypeName || '--'}}
              </el-button> -->
              <template v-if="scope.row.childTaskTypeName">
                <el-tooltip
                  class="box-item"
                  effect="dark"
                  :content="scope.row.childTaskTypeName"
                  placement="top"
                >
                  <el-button :icon="useRenderIcon(BookmarkFill)" size="small" type="text" link></el-button>
                </el-tooltip>
              </template>

              <!-- <el-tag size="small" class="ml-[2px]" v-if="scope.row.taskType > 1" @click="showAttachment(scope.row)">查看</el-tag> -->
            </template>
            <template #attachment="scope">
              <!-- <el-button class="reset-margin" link type="primary" :size="size"
                @click="seeDetail('清单', scope.row)" >
                清单
              </el-button>
              <el-button class="reset-margin" link type="primary" :size="size"
                @click="seeDetail('技术协议', scope.row)" >
                技术协议
              </el-button> -->
              <el-popover placement="top" >
                <template #reference>
                  <el-button size="small">附件</el-button>
                </template>
                <div class="flex-bc">
                  <el-button class="reset-margin" link type="primary" :size="size"
                    @click="seeDetail('清单', scope.row)" >
                    清单
                  </el-button>
                  <el-button class="reset-margin" link type="primary" :size="size"
                    @click="seeDetail('技术协议', scope.row)" >
                    技术协议
                  </el-button>
                </div>

              </el-popover>
            </template>

					</pure-table>
          </div>
				</template>
        </PureTableBar>
		</div>
    </keep-alive>
    <el-dialog
      v-model="dialogDetail"
      title="任务详情"
      width="1000px"
    >
      <div class="">
        <el-table
          ref="tableRef"
          :data="detailData"
          :header-cell-style="{background: 'var(--el-fill-color-light)',
          color: 'var(--el-text-color-primary)'}"
          show-overflow-tooltip
          row-key="taskId"
          :tree-props="{ children: 'childrens', hasChildren: 'hasChildren' }"
          default-expand-all
          border
        >
          <el-table-column label="任务阶段" width="150">
            <template #default="scope">{{ scope.row.taskTypeName ?? '--' }}</template>
          </el-table-column>
          <el-table-column label="任务状态" width="90">
            <template #default="scope">
              <el-tag type="info" v-if="scope.row.status === 0">未开始</el-tag>
              <el-tag type="warning" v-if="scope.row.status === 1">进行中</el-tag>
              <el-tag v-if="scope.row.status === 2">挂起跳过</el-tag>
              <el-tag type="success" v-if="scope.row.status === 3">已完成</el-tag>
              <el-tag type="danger" v-if="scope.row.status === 4">已关闭</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="计划日期/实际日期" min-width="240">
            <template #default="scope">
              <div>
                <span>计划日期：</span>
                <span>{{ scope.row.planStartDate ?? '--' }} 至 {{ scope.row.planEndDate ?? '--' }}</span>
              </div>
              <div>
                <span>实际日期：</span>
                <span>{{ scope.row.realStartDate ?? '--' }} 至 {{ scope.row.realEndDate ?? '--' }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="负责人" min-width="120">
            <template #default="scope">
              <div class="assigneds">
                <span v-for="(item, curr) in scope.row.assigneds" :key="curr" class="str">
                  {{item.user?.name}}<span>, </span>
                </span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="附件" prop="planStartDate" width="80">
            <template #default="{row}">
              <div class="flex" v-if="row.taskType !== 1030000">
                <el-button @click="openFile(row)" size="small">查看</el-button>
              </div>
              <div class="flex" v-else>
                --
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>


      <template #footer>
        <span class="dialog-footer">
          <!-- <el-button @click="dialogDetail = false">取消</el-button> -->
          <el-button type="primary" @click="dialogDetail = false">
            关闭
          </el-button>
        </span>
      </template>
    </el-dialog>
	</div>
</template>

<style scoped lang="scss">
	.main-content {
		margin: 10px 10px 0 !important;

	}
  :deep(.el-scrollbar__view) {
    display: block !important;
    width: 100%;
  }
  :deep(.el-table__body) {
    width: 100% !important;
  }
  .assigneds {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  .assigneds .str:last-child span{
    display: none;
  }
  .taskMyActive {
    border-color: #409eff;
    // padding: 4px 10px;
    color: #409eff;
  }
  // /* 提升展开行的层级 */
  // :deep(.el-table__expanded-cell) {
  //   z-index: 500 !important;
  //   position: relative;
  //   background: #fff;
  // }

  // /* 固定列需要更高层级 */
  // :deep(.el-table__fixed-right),
  // :deep(.el-table__fixed) {
  //   z-index: 500 !important;
  //   visibility: hidden;
  // }

  // :deep(.el-scrollbar__view) {
  //   width: 100%;
  // }
  // :deep(.is-left.el-table__cell:nth-last-of-type(2)) {
  //   border-right: none;
  // }

  :deep(.tableBox .el-table--default) {
    height: auto !important;
  }
  .dialogLabel {
    min-width: 90px;
    text-align: right;
  }
  .tableBox {
    position: sticky;
    left: 0;
    z-index: 3; /* 确保嵌套表格在主表格之上 */
  }
  :deep(.tableBox .el-table__body .el-table__row--level-1 td:nth-child(1)) {
    border-bottom: none;
  }
  :deep(.tableBox .el-table .custom-row-tr + .el-table__row--level-1 + .el-table__row--level-1 + .el-table__row--level-1 td:nth-child(1)),
  :deep(.tableBox .el-table .custom-row-tr + .el-table__row--level-1 + .el-table__row--level-1 + .el-table__row--level-1 + .el-table__row--level-1 + .el-table__row--level-1 + .el-table__row--level-1 td:nth-child(1)){
    border-bottom: 1px solid #ebeef5;
  }
</style>
